import React, { useEffect, useState } from 'react'
import axios from '../../api/axios'
import { Image, List,NavBar,SearchBar } from 'antd-mobile'
import {RightOutline} from 'antd-mobile-icons'
import { useNavigate, Outlet } from 'react-router-dom'
import useLoash from '../../hooks/useLoash';
function Index() {
     let navigate = useNavigate()
    const [list,setList]=useState([])
    const [searchlist, setSearchlist] = useState([])
    const [hislist, setHislist] = useState(JSON.parse(localStorage.getItem('hislist')) || [])
    const getList=async()=>{
const res=await axios.get('/serice/list')
console.log(res);
const {data}=res.data
setList(data)
    }
    useEffect(()=>{
      getList()  
    },[])
    const handelsearch =useLoash(async (val) => {
        if (val == '') {
            setSearchlist([])
            return
        }
        const res = await axios.get('/serice/list')
        console.log(res);
        const { data } = res.data
        setSearchlist([...searchlist,...data])
        const newlist=[val,...hislist]
        console.log(newlist);
        const ind=newlist.lastIndexOf(val)
        if(ind!==0){
            newlist.splice(ind,1)
        }
        setHislist(newlist)
        localStorage.setItem('hislist',JSON.stringify(newlist))
    },1000) 
    const goser=()=>{
        navigate('/service')
    }
  return (
    <div>
        <NavBar onBack={()=>navigate('/')}>发消息</NavBar>
        <SearchBar placeholder='关键词' onChange={(val) => handelsearch(val)} /> 
        <List header=''>
      {searchlist.length>0 && searchlist.map((item,ind) => (
        <List.Item
          key={item.name}
          prefix={
            <Image
              src={item.avatar}
              style={{ borderRadius: 20 }}
              fit='cover'
              width={40}
              height={40}
            />
          }
          description={item.usemes}
        >
          {item.name}
        </List.Item>
      ))}
    </List>
     <List header='用户列表'>
      {list.length>0 && list.map((item,ind) => (
        <List.Item
        onClick={()=>goser()}
          key={item.name}
          prefix={
            <Image
              src={item.avatar}
              style={{ borderRadius: 20 }}
              fit='cover'
              width={40}
              height={40}
            />
          }
          description={item.usemes}
        >
          {item.name}
        </List.Item>
      ))}
    </List>
    </div>
  )
}

export default Index
